import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { useCool } from "/@/cool";
import { useUi } from "/$/cool-ui";
import { useUserStore } from "/@/cool/store/user";

export interface OrderGoods {
	id?: number;
	count: number;
	spec: {
		id?: number;
		stock?: number;
		price?: number;
	};
	goodsInfo: Eps.GoodsInfoEntity;
	checked?: boolean;
	selected?: boolean;
}

export interface FullReductionDetail {
	id: number;
	billSn: number;
	taxAmount: number;
	billNo: string;
	dedRate: number;
	status: number;
	description: string;
}

export interface FullReductionPromotion {
	billNo: string;
	promName: string;
	promType: string;
	status: number;
	startTime: string;
	endTime: string;
	details: FullReductionDetail[];
}

// 获取最小数量
function getMinQuantity(goods: Eps.GoodsInfoEntity): number {
	// 如果是中包装且不支持拆零，最小数量为midpack
	if (goods.midpack && goods.midpack > 1 && goods.isMidpackSaleDisabled === 1) {
		return goods.midpack;
	}
	return 1;
}

// 获取数量步长
function getQuantityStep(goods: Eps.GoodsInfoEntity): number {
	// 如果是中包装且不支持拆零，步长为midpack
	if (goods.midpack && goods.midpack > 1 && goods.isMidpackSaleDisabled === 1) {
		return goods.midpack;
	}
	return 1;
}

// 验证数量是否有效
function isValidQuantity(goods: Eps.GoodsInfoEntity, count: number): boolean {
	// 如果是中包装且不支持拆零，数量必须是midpack的倍数
	if (goods.midpack && goods.midpack > 1 && goods.isMidpackSaleDisabled === 1) {
		return count % goods.midpack === 0;
	}
	return true;
}

// 调整数量到最近的有效值
function adjustToValidQuantity(goods: Eps.GoodsInfoEntity, count: number): number {
	if (goods.midpack && goods.midpack > 1 && goods.isMidpackSaleDisabled === 1) {
		const midpack = goods.midpack;
		// 计算向上和向下的倍数
		const lowerMultiple = Math.floor(count / midpack) * midpack;
		const upperMultiple = Math.ceil(count / midpack) * midpack;

		// 如果向上的倍数不超过库存，优先选择向上
		if (upperMultiple <= Number(goods.storNum || 0)) {
			return upperMultiple;
		}
		// 否则选择向下的倍数，但不能小于最小数量
		else if (lowerMultiple >= getMinQuantity(goods)) {
			return lowerMultiple;
		}
		// 如果都不满足，返回最小数量
		else {
			return getMinQuantity(goods);
		}
	}
	return count;
}

// 购物车
export const useShoppingCart = defineStore("shopping-cart", () => {
	const list = ref<OrderGoods[]>([]);
	const fullReductions = ref<FullReductionPromotion[]>([]);
	const isLoading = ref(false);
	const error = ref<string | null>(null);

	const { service } = useCool();
	const user = useUserStore();
	const ui = useUi();

	// 购物车数量
	const num = computed(() => {
		return list.value.length;
	});

	// 购物车总价
	const cartTotal = computed(() => {
		return list.value.reduce((sum, item) => {
			const price = Math.round(Number(item.goodsInfo.price || 0) * 100) / 100;
			return Math.round((sum + price * item.count) * 100) / 100;
		}, 0);
	});

	// 选中商品的总价
	const selectedTotalAmount = computed(() => {
		return list.value
			.filter((item) => item.checked)
			.reduce((sum, item) => {
				const price = Math.round(Number(item.goodsInfo.price || 0) * 100) / 100;
				return Math.round((sum + price * item.count) * 100) / 100;
			}, 0);
	});

	// 活跃的满减促销
	const activeFullReductions = computed(() => {
		const now = new Date();
		return fullReductions.value.filter((promotion) => {
			const startTime = new Date(promotion.startTime);
			const endTime = new Date(promotion.endTime);
			return promotion.status === 1 && now >= startTime && now <= endTime;
		});
	});

	// 计算最优折扣
	const bestDiscount = computed(() => {
		if (selectedTotalAmount.value === 0 || activeFullReductions.value.length === 0) {
			return null;
		}

		let bestRate = 100;
		let bestDetail: FullReductionDetail | null = null;
		let bestBillNo: string | null = null;

		activeFullReductions.value.forEach((reduction) => {
			const applicableDetails = reduction.details
				.filter((detail) => selectedTotalAmount.value >= Number(detail.taxAmount))
				.sort((a, b) => Number(a.dedRate) - Number(b.dedRate));

			if (applicableDetails.length > 0) {
				const detail = applicableDetails[0];
				if (Number(detail.dedRate) < bestRate) {
					bestRate = Number(detail.dedRate);
					bestDetail = detail;
					bestBillNo = reduction.billNo;
				}
			}
		});

		return bestDetail ? { rate: bestRate, detail: bestDetail, billNo: bestBillNo || "" } : null;
	});

	// 折扣金额
	const discountAmount = computed(() => {
		if (!bestDiscount.value) return 0;
		return selectedTotalAmount.value * (1 - bestDiscount.value.rate / 100);
	});

	// 最终价格
	const finalPrice = computed(() => {
		return selectedTotalAmount.value - discountAmount.value;
	});

	// 获取购物车列表
	async function fetchCartList() {
		if (!user.token) {
			list.value = [];
			return;
		}

		try {
			isLoading.value = true;
			error.value = null;
			const response = await service.order.cart.listCart();
			if (response) {
				list.value = response.map((item: any) => ({
					...item,
					checked: item.selected || false,
					spec: {
						id: item.goodsInfo?.id,
						stock: item.goodsInfo?.storNum,
						price: item.goodsInfo?.price,
					},
				}));
			}
		} catch (err: any) {
			error.value = err.message || "获取购物车失败";
			console.error("获取购物车失败:", err);
		} finally {
			isLoading.value = false;
		}
	}

	// 添加到购物车
	async function add(data: { goodsId: string; count: number }) {
		if (!user.token) {
			ui.showToast("请先登录");
			return false;
		}

		try {
			const validCount = adjustToValidQuantity(data as any, data.count);
			const response = await service.order.cart.addCart({
				goodsId: data.goodsId,
				count: validCount,
			});

			if (response.code === 1000) {
				await fetchCartList();
				return true;
			} else {
				ui.showToast(response.message || "添加购物车失败");
				return false;
			}
		} catch (err: any) {
			ui.showToast(err.message || "添加购物车失败");
			console.error("添加购物车失败:", err);
			return false;
		}
	}

	// 更新商品数量
	async function updateQuantity(id: number, count: number) {
		if (!user.token) {
			ui.showToast("请先登录");
			return false;
		}

		try {
			await service.order.cart.updateCount({ id, count });

			return true;
		} catch (err: any) {
			console.error("更新数量失败:", err);
			return false;
		}
	}

	// 删除商品
	async function del(id: number) {
		if (!user.token) {
			ui.showToast("请先登录");
			return false;
		}

		try {
			const response = await service.order.cart.remove({ ids: [id] });
			if (response) {
				await fetchCartList();
				return true;
			}
			return false;
		} catch (err: any) {
			console.error("删除商品失败:", err);
			return false;
		}
	}

	// 清空购物车
	async function clear() {
		if (!user.token) {
			ui.showToast("请先登录");
			return false;
		}

		try {
			const response = await service.order.cart.clear();
			if (response) {
				list.value = [];
				return true;
			}
			return false;
		} catch (err: any) {
			console.error("清空购物车失败:", err);
			return false;
		}
	}

	// 从购物车创建订单
	async function createOrderFromCart(cartIds: number[], mjBillNo?: string) {
		if (!user.token) {
			ui.showToast("请先登录");
			return false;
		}

		try {
			const response = await service.order.info.createFromCart({ cartIds, mjBillNo });
			if (response) {
				await fetchCartList();
				return response;
			}
			return false;
		} catch (err: any) {
			console.error("创建订单失败:", err);
			throw err;
		}
	}

	// 获取满减促销
	async function fetchFullReductions() {
		try {
			const response = await service.goods.promo.getComboDetailsByType({ promType: "MJ" });
			if (response?.list) {
				fullReductions.value = response.list.filter(
					(p: any) => p.promType === "MJ" || p.promType === "满减"
				);
			}
		} catch (error) {
			console.error("获取满减促销失败:", error);
		}
	}

	// 监听用户登录状态
	watch(
		() => user.token,
		(newToken) => {
			if (newToken) {
				fetchCartList();
				fetchFullReductions();
			} else {
				list.value = [];
				fullReductions.value = [];
			}
		}
	);

	return {
		list,
		num,
		cartTotal,
		selectedTotalAmount,
		activeFullReductions,
		bestDiscount,
		discountAmount,
		finalPrice,
		fullReductions,
		isLoading,
		error,
		add,
		del,
		clear,
		updateQuantity,
		fetchCartList,
		createOrderFromCart,
		fetchFullReductions,
		getMinQuantity,
		getQuantityStep,
		isValidQuantity,
		adjustToValidQuantity,
	};
});
